//
//  BubbleChatView2.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/5/2.
//  左右镜像的气泡聊天框
//

import SwiftUI
import Kingfisher

struct BubbleChatView2: View {
    @State var str: String
    @State var sound: SoundBean? = nil
    @State var bean: BubbleBean
    @State var iconCenterLeading : CGFloat = 0
    @State var iconCenterTrailing : CGFloat = 0
    @State var iconCenterTop : CGFloat = 0
    @State var iconCenterBottom : CGFloat = 0
    @Binding var isStartedSound:Bool //语音播放状态
    var clickSound: (() -> Void)? = nil//语音点击
    
    var body: some View {
        ZStack {
            ZStack {
                if let sound = sound {
                    ChatItemVoiceView(bean: sound, color: Color.hex(bean.textColor), isStarted: $isStartedSound) {
                        clickSound?()
                    }
                } else {
                    Text(str)
                        .font(.system(size: 14))
                        .foregroundColor(Color.hex(bean.textColor))
                }
            }.padding(.leading, bean.trailing)
                .padding(.trailing, bean.leading)
                .padding(.top, bean.top)
                .padding(.bottom, bean.bottom)
            
            
        }
        .frame(minWidth: bean.minWith, minHeight: bean.minHeight)
        .padding(.leading , iconCenterTrailing)
        .padding(.trailing, iconCenterLeading)
        .padding(.top , iconCenterTop)
        .padding(.bottom , iconCenterBottom)
        .background(
            BubbleBgView2(bubble: bean)
        ).onAppear {
            iconCenterLeading = bean.iconCenter?.leading ?? 0
            iconCenterTrailing = bean.iconCenter?.trailing ?? 0
            iconCenterTop = bean.iconCenter?.top ?? 0
            iconCenterBottom = bean.iconCenter?.bottom ?? 0
        }
    }
    
    // 角标视图构建函数
    private func cornerImage(name: ImageResource, offset: CGSize) -> some View {
        Image(name)
            .offset(offset)
    }
}

private let previewBean: BubbleBean = {
    BubbleExt.getBubble(id: "28") ?? BubbleBean()
}()

//#Preview {
//    BubbleChatView2(str: "哈喽",bean: previewBean, isStartedSound: $isStartedSound).background(.bg)
//}

//定义预览提供者
struct BubbleChatView2_Previews: PreviewProvider {

    static var previews: some View {
        @State var isStartedSound:Bool = false  //语音播放
        //使用预览共享配置
        configurePreviewEnvironment(for: BubbleChatView2(str: "哈喽",bean: previewBean, isStartedSound: $isStartedSound).background(.bg))
    }
}
